package com.itheima.exception;

import com.itheima.entity.Result;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 2. 自定义类异常处理
 *
 * @author Chengfei
 * @date 2020/08/18
 */
@ControllerAdvice
public class ExceptionAdvice {

    /**
     * 空指针异常
     * @param ex 空指针异常
     * @return
     */
    @ExceptionHandler(NullPointerException.class)
    @ResponseBody
    public String doNullException(Exception ex) {
        System.out.println("空指针异常:" + ex.getMessage());
        return "空指针异常";
    }

    /**
     * 访问拒绝异常  当用户名,密码错误,拦截后处理
     * @param ex  访问拒绝异常
     * @return
     */
    @ExceptionHandler(AccessDeniedException.class)
    @ResponseBody
    public Result doAccessDeniedException(Exception ex) {
        System.out.println("没有访问权限:" + ex.getMessage());//Access is denied
        return new Result(false,"您没有此项权限");
    }

    //其他错误

    /**
     * 其他异常
     * @param ex  其他异常
     * @return
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Result doException(Exception ex) {
        ex.printStackTrace();
        return new Result(false,"其他错误");
    }

}
